<?php
// 数据库管理页面
require_once 'database.php';

// 简单的密码保护
$admin_password = 'admin123';
$is_authenticated = false;

session_start();

if (isset($_POST['password'])) {
    if ($_POST['password'] === $admin_password) {
        $_SESSION['db_admin_authenticated'] = true;
        $is_authenticated = true;
    }
} else {
    $is_authenticated = $_SESSION['db_admin_authenticated'] ?? false;
}

// 处理退出登录
if (isset($_GET['logout'])) {
    session_destroy();
    header('Location: db_admin.php');
    exit;
}

if (!$is_authenticated) {
    ?>
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>数据库管理员登录</title>
        <style>
            body { font-family: Arial, sans-serif; max-width: 400px; margin: 100px auto; padding: 20px; background-color: #f5f5f5; }
            .login-form { background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
            input[type="password"] { width: 100%; padding: 12px; margin: 10px 0; border: 1px solid #ddd; border-radius: 5px; box-sizing: border-box; }
            button { background-color: #007bff; color: white; padding: 12px 24px; border: none; border-radius: 5px; cursor: pointer; width: 100%; }
            button:hover { background-color: #0056b3; }
        </style>
    </head>
    <body>
        <div class="login-form">
            <h2>数据库管理员登录</h2>
            <form method="post">
                <input type="password" name="password" placeholder="请输入管理员密码" required>
                <button type="submit">登录</button>
            </form>
            <p style="color: #666; font-size: 14px; margin-top: 20px;">默认密码: admin123</p>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// 处理操作
$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    try {
        $db = new Database();
        
        switch ($_POST['action']) {
            case 'delete_visitor':
                if (isset($_POST['visitor_id'])) {
                    $visitor = $db->getVisitorById($_POST['visitor_id']);
                    if ($visitor && !empty($visitor['photo_filename'])) {
                        // 删除照片文件
                        $photoPath = 'visitor_data/photos/' . $visitor['photo_filename'];
                        if (file_exists($photoPath)) {
                            unlink($photoPath);
                        }
                    }
                    $db->deleteVisitor($_POST['visitor_id']);
                    $message = '访客数据删除成功';
                    $messageType = 'success';
                }
                break;
                
            case 'cleanup_old':
                $days = intval($_POST['cleanup_days'] ?? 30);
                $count = $db->cleanupOldData($days);
                $message = "成功清理了 {$count} 条超过 {$days} 天的旧数据";
                $messageType = 'success';
                break;
        }
    } catch (Exception $e) {
        $message = '操作失败: ' . $e->getMessage();
        $messageType = 'error';
    }
}

// 获取数据
try {
    $db = new Database();
    $visitors = $db->getAllVisitors(50); // 限制显示50条
    $stats = $db->getVisitorStats();
} catch (Exception $e) {
    $visitors = [];
    $stats = ['total' => 0, 'last_24h' => 0, 'last_7d' => 0, 'today' => 0];
    $message = '数据库连接失败: ' . $e->getMessage();
    $messageType = 'error';
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据库管理</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .header {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .stats {
            display: flex;
            gap: 20px;
            margin-bottom: 20px;
        }
        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            flex: 1;
            text-align: center;
        }
        .stat-number {
            font-size: 2em;
            font-weight: bold;
            color: #007bff;
        }
        .actions {
            background: white;
            padding: 20px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        .btn {
            background-color: #007bff;
            color: white;
            padding: 8px 16px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            text-decoration: none;
            display: inline-block;
            margin: 5px;
        }
        .btn:hover {
            background-color: #0056b3;
        }
        .btn-danger {
            background-color: #dc3545;
        }
        .btn-danger:hover {
            background-color: #c82333;
        }
        .btn-warning {
            background-color: #ffc107;
            color: #212529;
        }
        .btn-warning:hover {
            background-color: #e0a800;
        }
        .table {
            background: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        table {
            width: 100%;
            border-collapse: collapse;
        }
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        .message {
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        .message.success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .message.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .logout {
            float: right;
            background: #dc3545;
            color: white;
            padding: 8px 16px;
            text-decoration: none;
            border-radius: 5px;
        }
        .logout:hover {
            background: #c82333;
        }
        .form-inline {
            display: inline-block;
            margin: 5px;
        }
        .form-inline input {
            padding: 6px;
            border: 1px solid #ddd;
            border-radius: 3px;
            margin-right: 5px;
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>数据库管理系统</h1>
        <a href="?logout=1" class="logout">退出登录</a>
        <a href="admin.php" class="btn" style="float: right; margin-right: 10px;">返回主管理页面</a>
        <div style="clear: both;"></div>
    </div>

    <?php if ($message): ?>
        <div class="message <?php echo $messageType; ?>">
            <?php echo htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>

    <div class="stats">
        <div class="stat-card">
            <div class="stat-number"><?php echo $stats['total']; ?></div>
            <div>总记录数</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo $stats['last_24h']; ?></div>
            <div>24小时内</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo $stats['last_7d']; ?></div>
            <div>7天内</div>
        </div>
        <div class="stat-card">
            <div class="stat-number"><?php echo $stats['today']; ?></div>
            <div>今日新增</div>
        </div>
    </div>

    <div class="actions">
        <h3>数据库操作</h3>
        
        <form method="post" class="form-inline" onsubmit="return confirm('确定要清理旧数据吗？此操作不可恢复！')">
            <input type="hidden" name="action" value="cleanup_old">
            <input type="number" name="cleanup_days" value="30" min="1" max="365" placeholder="天数">
            <button type="submit" class="btn btn-warning">清理旧数据</button>
        </form>
        
        <a href="test.php" class="btn">系统测试</a>
        <a href="index.php" class="btn">访客页面</a>
    </div>

    <div class="table">
        <h3 style="padding: 20px; margin: 0; background-color: #f8f9fa;">访客数据列表 (最近50条)</h3>
        
        <?php if (empty($visitors)): ?>
            <div style="padding: 50px; text-align: center; color: #6c757d;">
                <h3>暂无数据</h3>
                <p>数据库中还没有访客记录</p>
            </div>
        <?php else: ?>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>时间</th>
                        <th>IP地址</th>
                        <th>位置</th>
                        <th>照片</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($visitors as $visitor): ?>
                        <tr>
                            <td><?php echo htmlspecialchars(substr($visitor['id'], -8)); ?>...</td>
                            <td><?php echo htmlspecialchars($visitor['timestamp']); ?></td>
                            <td><?php echo htmlspecialchars($visitor['ip_address']); ?></td>
                            <td>
                                <a href="https://apis.map.qq.com/uri/v1/marker?marker=coord:<?php echo $visitor['latitude']; ?>,<?php echo $visitor['longitude']; ?>;title:访客位置;addr:纬度<?php echo $visitor['latitude']; ?>,经度<?php echo $visitor['longitude']; ?>&referer=访客追踪系统" 
                                   target="_blank" style="color: #007bff;">
                                    <?php echo number_format($visitor['latitude'], 4); ?>, <?php echo number_format($visitor['longitude'], 4); ?>
                                </a>
                            </td>
                            <td>
                                <?php if (!empty($visitor['photo_filename'])): ?>
                                    <a href="visitor_data/photos/<?php echo htmlspecialchars($visitor['photo_filename']); ?>" 
                                       target="_blank" style="color: #28a745;">查看照片</a>
                                <?php else: ?>
                                    <span style="color: #6c757d;">无照片</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <form method="post" style="display: inline;" 
                                      onsubmit="return confirm('确定要删除这条记录吗？此操作不可恢复！')">
                                    <input type="hidden" name="action" value="delete_visitor">
                                    <input type="hidden" name="visitor_id" value="<?php echo htmlspecialchars($visitor['id']); ?>">
                                    <button type="submit" class="btn btn-danger" style="padding: 4px 8px; font-size: 12px;">删除</button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
</body>
</html>